package com.example.Service;

import cn.dev33.satoken.stp.StpUtil;
import com.example.Entity.Dto.UserInfo;
import com.example.Utils.RedisUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * 基类，内置方法获取用户的一些信息
 */
public class BaseService {
    @Resource
    RedisUtils redisUtils;

    /**
     * 获取登陆人的信息
     * @return UserInfo
     */
    public UserInfo GetSessionInfo() {
        String userid = StpUtil.getLoginIdAsString();
        String userInfostring = redisUtils.getString(userid);
        ObjectMapper objectMapper = new ObjectMapper();
        UserInfo userInfo = null;
        try {
            userInfo = objectMapper.readValue(userInfostring, UserInfo.class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("请重新登录");
        }
        return userInfo;
    }

    /**
     * 设置用户信息
     * @param userInfo 用户信息
     * @return boolean
     */
    public boolean SetSessionInfo(UserInfo userInfo) {
        ObjectMapper objectMapper = new ObjectMapper();
        String u = null;
        try {
            u = objectMapper.writeValueAsString(userInfo);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e.getMessage());
        }
        return redisUtils.setString(userInfo.getId(),u,86400);
    }

    /**
     * 生成UUID
     * @return String
     */
    public String GetUUID(){
        return UUID.randomUUID().toString();
    }
}
